import { getHomeBannerApi, getHomeDataLengthApi, getHomeVisiteApi } from '@/api'
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'

// 获得轮播图数据
export const fetchHomeBanners = createAsyncThunk(
  'home/fetchHomeBanners',
  async (_, { dispatch }) => {
    const banners = await getHomeBannerApi()
    dispatch(setBannersReducers(banners))
  }
)

// 获得数据模块中的数据
export const fetchHomeVisiteData = createAsyncThunk(
  'home/fetchHomeVisiteData',
  async (_, { dispatch }) => {
    const res = await getHomeVisiteApi()
    dispatch(setHomeVisiteData(res))
  }
)

// 获得数据长度
export const fetchHomeVisiteDataLength = createAsyncThunk(
  'home/fetchHomeVisiteDataLength',
  async (_, { dispatch }) => {
    const res = await getHomeDataLengthApi()
    dispatch(setDataLength(res))
  }
)

interface IState {
  banners: any[]
  visiteData: any
  dataLength: any
}

const initialState: IState = {
  banners: [],
  visiteData: 0,
  dataLength: []
}

const homeStore = createSlice({
  name: 'home',
  initialState: initialState,
  reducers: {
    // 设置首页轮播图
    setBannersReducers(state, action) {
      state.banners = action.payload
    },
    // 设置数据模块中的数据
    setHomeVisiteData(state, action) {
      state.visiteData = action.payload
    },
    // 设置数据长度
    setDataLength(state, action) {
      state.dataLength = action.payload
    }
  }
})

export const { setBannersReducers, setHomeVisiteData, setDataLength } = homeStore.actions

export default homeStore.reducer
